<template>
    <div class="contact-container">
        <div class="mb15">
            <TableSearch :search="state.tableData.search" @search="onSearch" />

            <el-button class="flex-end" size="default" type="success" @click="editContact('add')">
                <el-icon>
                    <ele-FolderAdd />
                </el-icon>
                新增联系人
            </el-button>
        </div>

        <div class="contact-padding">
            <Table ref="tableRef" v-bind="state.tableData" class="contact" @pageChange="onTablePageChange">
                <template v-slot:tableOperate="row">
                    <el-popconfirm title="确定删除吗？" @confirm="onTableDelRow(row.row)">
                        <template #reference>
                            <el-button size="small" text type="primary">删除</el-button>
                        </template>
                    </el-popconfirm>

                    <el-button size="small" text type="primary" @click="editContact('edit', row.row.id)">
                        编辑
                    </el-button>
                </template>
            </Table>
        </div>
        <ContactDialog ref="contactDialogRef" @refresh="getTableData()" />
    </div>
</template>

<script setup lang="ts" name="Contact">
import { defineAsyncComponent, reactive, ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useContactApi } from '/@/api/mainData/contact';

// 引入 api 请求接口
const contactApi = useContactApi();

// 引入组件
const TableSearch = defineAsyncComponent(() => import('/@/components/table/search.vue'));
const Table = defineAsyncComponent(() => import('/@/components/table/index.vue'));
const ContactDialog = defineAsyncComponent(() => import('/@/views/mainData/contact/component/contactDialog.vue'));

// 定义变量内容
const tableRef = ref<RefType>();
const contactDialogRef = ref();
const state = reactive<TableDemoState>({
    tableData: {
        // 列表数据（必传）
        data: [],
        // 表头内容（必传，注意格式）
        header: [
            { key: 'name', colWidth: '', title: '姓名', type: 'text', isCheck: true },
            { key: 'phoneNum', colWidth: '', title: '手机号', type: 'text', isCheck: true },
            { key: 'email', colWidth: '', title: '邮箱', type: 'text', isCheck: true },
        ],
        // 配置项（必传）
        config: {
            total: 0,               // 列表总数
            loading: true,          // loading 加载
            isBorder: false,        // 是否显示表格边框
            isSerialNo: true,       // 是否显示表格序号
            isSelection: false,     // 是否显示表格多选
            isOperate: true,        // 是否显示表格操作栏
        },
        // 搜索表单，动态生成（传空数组时，将不显示搜索，注意格式）
        search: [
            { label: '姓名', prop: 'name', placeholder: '支持模糊搜索', required: false, type: 'input', defaultVal: '' },
        ],
        // 搜索参数（不用传，用于分页、搜索时传给后台的值，`getTableData` 中使用）
        param: {
            pageNum: 1,
            pageSize: 10,
        },
        // 打印标题
        printName: '联系方式',
    },
});

//搜索
const onSearch = (data: EmptyObjectType) => {
    getTableData(data);
};

const props = defineProps({
    bizId: {
        type: String,
        default: () => '',
    },
    type: {
        type: Number,
        default: () => '',
    }
});

// 初始化列表数据
async function getTableData(data?: EmptyObjectType) {
    console.log('initContact');
    if ('' == props.bizId) {
        state.tableData.config.loading = false;
        return;
    }
    state.tableData.config.loading = true;

    const param = Object.assign({ type: props.type, bizId: props.bizId }, state.tableData.param, { ...data });
    const contactData = await contactApi.queryContactList(param);
    if (contactData.data == null)
        return Promise.resolve(true);

    const contactDataRows: Contact[] = contactData.data.rows;
    const showContactData = [];
    if (undefined != contactDataRows) {
        for (const item of contactDataRows) {
            const showContactItem = {
                id: item.id,
                name: item.name,
                phoneNum: item.phoneNum,
                email: item.email,
            }
            showContactData.push(showContactItem);
        }
    }

    state.tableData.data = showContactData;
    state.tableData.config.total = contactData.data.total;
    setTimeout(() => {
        state.tableData.config.loading = false;
    }, 500);
};

// 删除当前项回调
async function onTableDelRow(row: EmptyObjectType) {
    const deleteItem = {
        id: row.id,
    }
    await contactApi.deleteContact(deleteItem);

    ElMessage.success(`删除${row.name}成功！`);
    getTableData();
};

// 编辑联系人
async function editContact(operateType: string, contactId?: number) {
    contactDialogRef.value.openDialog(operateType, props.type, props.bizId, contactId);
}

// 分页改变时回调
const onTablePageChange = (page: TableDemoPageType) => {
    state.tableData.param.pageNum = page.pageNum;
    state.tableData.param.pageSize = page.pageSize;
    getTableData();
};

// 页面加载时
onMounted(() => {
    getTableData();
});
</script>

<style scoped lang="scss">
.flex-end {
    /* 将内容推到右侧 */
    display: flex;
    margin-left: auto;
}
</style>
